﻿angular.module('Finance', [
   'ui.router',
   'ui.bootstrap'
]);

angular.module('Finance').config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider
      .otherwise('/home');

    $stateProvider
         .state('home', {
             url: '/home',
             abstract: false,
             views: {
                 "main": {
                     template: ''
                 }
             }
         })
         .state('banks', {
             url: '/banks',
             views: {
                 "main": {
                     templateUrl: 'Bank/Index',
                     controller: function ($scope, Bank) {

                         $scope.loadBanks = function () {

                             var self = $scope;
                             Bank.query($scope.name, 0, 20).then(function (result) {
                                 self.banks = result.data;
                             });
                         }

                         $scope.loadBanks();
                     }
                 }
             }
         }).state('banks.new', {
             url: '/new',
             views: {
                 "manager": {
                     templateUrl: 'Bank/Create',
                     controller: function ($scope, Bank) {

                         $scope.bank = { Name: "" };

                         $scope.createBank = function () {

                             if ($scope.bankForm.$valid) {

                                 Bank.save($scope.bank).then(function () {
                                     $scope.$state.transitionTo('banks');
                                     $scope.loadBanks()
                                 }, function (result) {
                                     $scope.bindErrors($scope.bankForm, result.data);
                                 });
                             }
                         }

                         $scope.cancel = function () {
                             $scope.$state.transitionTo('banks');
                             $scope.loadBanks()
                         }
                     }
                 }               
             }
         }).state('banks.edit', {
             url: '/{id}',
             views: {
                 "manager": {
                     templateUrl: 'Bank/Create',
                     controller: function ($scope, Bank) {

                         Bank.get($scope.$stateParams.id).then(function (result) {
                             $scope.bank = result.data;
                         }, function () {
                             $scope.$state.transitionTo('banks');
                             $scope.loadBanks();
                         })

                         $scope.createBank = function () {

                             if ($scope.bankForm.$valid) {

                                 Bank.save($scope.bank).then(function () {
                                     $scope.$state.transitionTo('banks');
                                     $scope.loadBanks()
                                 }, function (result) {
                                     $scope.bindErrors($scope.bankForm, result.data);
                                 });
                             }
                         }

                         $scope.cancel = function () {
                             $scope.$state.transitionTo('banks');
                             $scope.loadBanks()
                         }
                     }
                 }
             }
         }).state('deposites', {
             url: '/deposites',
             views: {
                 "main": {
                     templateUrl: 'Deposit/Index',
                     controller: function ($scope, Deposit, Bank) {

                         $scope.loadDeposites = function () {

                             var self = $scope;
                             Deposit.query($scope.name, 0, 20).then(function (result) {
                                 self.deposites = result.data;
                             });
                         }

                         $scope.getBanks = function (val) {
                             return Bank.query(val, 0, 40).then(function (res) {
                                 return res.data;
                             });
                         }

                         $scope.cancel = function () {
                             $scope.$state.transitionTo('deposites');
                             $scope.loadDeposites()
                         }

                         $scope.remove = function (model) {
                             Deposit.remove(model).then(function (result) {
                                 $scope.$state.transitionTo('deposites');
                                 $scope.loadDeposites()
                             }, function () {

                             });
                         }

                         $scope.addDep = function (model) {
                             if (!model.PercentAmountDepends)
                                 model.PercentAmountDepends = [];
                             model.PercentAmountDepends.push({});
                         }

                         $scope.addPen = function (model) {
                             if (!model.PercentPenalties)
                                 model.PercentPenalties = [];
                             model.PercentPenalties.push({});
                         }

                         $scope.removeDep = function (model, dep) {
                             model.PercentAmountDepends.splice(model.PercentAmountDepends.indexOf(dep), 1);
                         }

                         $scope.removePen = function (model, dep) {
                             model.PercentPenalties.splice(model.PercentPenalties.indexOf(dep), 1);
                         }

                         $scope.loadDeposites();
                     }
                 }
             }
         }).state('deposites.new', {
             url: '/new',
            views: {
                "manager": {
                    templateUrl: 'Deposit/Create',
                    controller: function ($scope, Deposit, Bank) {

                        $scope.model = {  };

                        $scope.createModel = function () {

                            if ($scope.depositForm.$valid) {

                                Deposit.save($scope.model).then(function () {
                                    $scope.$state.transitionTo('deposites');
                                    $scope.loadDeposites()
                                }, function (result) {
                                    $scope.bindErrors($scope.depositForm, result.data);
                                });
                            }
                        }
                    }
                }
            }
         }).state('deposites.edit', {
             url: '/{id}',
             views: {
                 "manager": {
                     templateUrl: 'Deposit/Create',
                     controller: function ($scope, Deposit, Bank) {

                         Deposit.get($scope.$stateParams.id).then(function (result) {
                             $scope.model = result.data;
                         }, function () {
                             $scope.$state.transitionTo('deposites');
                             $scope.loadDeposites()
                         })


                         $scope.createModel = function () {

                             if ($scope.depositForm.$valid) {

                                 Deposit.save($scope.model).then(function () {
                                     $scope.$state.transitionTo('deposites');
                                     $scope.loadDeposites()
                                 }, function (result) {
                                     $scope.bindErrors($scope.depositForm, result.data);
                                 });
                             }
                         }
                     }
                 }
             }
         }).state('actives', {
             url: '/actives',
             views: {
                 "main": {
                     templateUrl: 'Active/Index'
                 }
             }
         }).state('actives.deposites', {
             url: '/deposites',
             views: {
                 "deposites": {
                     templateUrl: 'Active/Deposites',
                     controller: function ($scope, Active, Deposit) {

                         $scope.loadUserDeposites = function () {

                             var self = $scope;
                             Active.query($scope.name, 0, 20).then(function (result) {
                                 angular.forEach(result.data, function (item) {
                                     item.OpeningDate = $scope.toJavaScriptDate(item.OpeningDate);
                                     item.EndDate = $scope.toJavaScriptDate(item.EndDate);
                                 });
                                 self.userDeposites = result.data;
                             });
                         };

                        

                         $scope.loadDeposites = function (val) {

                             var self = $scope;
                             return Deposit.query(val, 0, 20).then(function (result) {
                                 return result.data;
                             });
                         }

                         $scope.remove = function (model) {
                             Active.remove(model).then(function (result) {
                                 $scope.$state.transitionTo('actives.deposites');
                                 $scope.loadUserDeposites()
                             }, function () {

                             });
                         }

                         $scope.showResults = function (model) {

                             Active.showResults(model).then(function (result) {
                                 model.ActualAmount = result.data;
                             }, function () {

                             });
                         }

                         $scope.cancel = function () {
                             $scope.$state.transitionTo('actives.deposites');
                             $scope.loadUserDeposites()
                         }

                         $scope.loadUserDeposites();
                     }
                 }
             }
         }).state('actives.deposites.new', {
             url: '/new',
             views: {
                 "manager": {
                     templateUrl: 'Active/NewUserDeposite',
                     controller: function ($scope, Deposit, Active) {

                         $scope.model = {};

                         $scope.createModel = function () {

                             if ($scope.userDepositForm.$valid) {

                                 Active.save($scope.model).then(function () {
                                     $scope.$state.transitionTo('actives.deposites');
                                     $scope.loadUserDeposites()
                                 }, function (result) {
                                     $scope.bindErrors($scope.userDepositForm, result.data);
                                 });
                             }
                         }

                         $scope.$watch('model.OpeningDate', function (val) {
                             if (val && $scope.model.Deposit) {
                                 var newDate = new Date($scope.model.OpeningDate);
                                 newDate.setMonth(newDate.getMonth() + $scope.model.Deposit.PeriodPayment);
                                 $scope.model.EndDate = newDate;
                             }
                         });

                         $scope.$watch('model.Deposit', function (val) {
                             if (val && val.PeriodPayment && $scope.model.OpeningDate) {
                                 var newDate = new Date($scope.model.OpeningDate);
                                 newDate.setMonth(newDate.getMonth() + $scope.model.Deposit.PeriodPayment);
                                 $scope.model.EndDate = newDate;
                             }
                         });
                     }
                 }
             }
         }).state('actives.deposites.edit', {
             url: '/{id}',
             views: {
                 "manager": {
                     templateUrl: 'Active/NewUserDeposite',
                     controller: function ($scope, Deposit, Active) {

                         $scope.model = {};

                         $scope.$watch('model.OpeningDate', function (val) {
                             if (val && $scope.model.Period) {
                                 var newDate = new Date($scope.model.OpeningDate);
                                 newDate.setMonth(newDate.getMonth() + $scope.model.Period);
                                 $scope.model.EndDate = newDate;
                             }
                         });

                         Active.get($scope.$stateParams.id).then(function (result) {
                             $scope.model = result.data;
                             $scope.model.OpeningDate = $scope.toJavaScriptDate($scope.model.OpeningDate);
                             $scope.model.EndDate = $scope.toJavaScriptDate($scope.model.EndDate);
                         }, function () {
                             $scope.$state.transitionTo('actives.deposites');
                             $scope.loadUserDeposites()
                         })

                         $scope.createModel = function () {

                             if ($scope.userDepositForm.$valid) {

                                 Active.save($scope.model).then(function () {
                                     $scope.$state.transitionTo('actives.deposites');
                                     $scope.loadUserDeposites()
                                 }, function (result) {
                                     $scope.bindErrors($scope.userDepositForm, result.data);
                                 });
                             }
                         }
                     }
                 }
             }
         }).state('accounting', {
             url: '/accounting',
             views: {
                 "main": {
                     templateUrl: 'Accounting/Index',
                     controller: function ($scope, Deposit) {
                         $scope.loadDeposites = function (val) {

                             return Deposit.query(val, 0, 20).then(function (result) {
                                 return result.data;
                             });
                         };
                     }
                 }
             }
         }).state('accounting.deposites', {
             url: '/deposites',
             views: {
                 "accounting": {
                     templateUrl: 'Accounting/Deposites',
                     controller: function ($scope, Deposit, Accounting) {

                         $scope.model = {};

                         $scope.calculate = function () {
                             if ($scope.depositForm.$valid) {
                                 Accounting.calculate($scope.model).then(function (result) {
                                     $scope.result = result.data.amount;
                                     $scope.byMonth = result.data.byMonth;
                                 });
                             }
                         }
                     }
                 }
             }
         }).state('accounting.effect', {
             url: '/effect',
             views: {
                 "accounting": {
                     templateUrl: 'Accounting/Effect',
                     controller: function ($scope, Deposit, Accounting) {

                         $scope.model = {};

                         $scope.calculate = function () {
                             if ($scope.depositForm.$valid) {
                                 Accounting.effect($scope.model).then(function (result) {
                                     $scope.result = result.data;
                                 });
                             }
                         }
                     }
                 }
             }
         }).state('accounting.yieldperiod', {
             url: '/yieldperiod',
             views: {
                 "accounting": {
                     templateUrl: 'Accounting/Yield',
                     controller: function ($scope, Deposit, Accounting) {

                         $scope.model = {};

                         $scope.calculate = function () {
                             if ($scope.depositForm.$valid) {
                                 Accounting.yieldperiod($scope.model).then(function (result) {
                                     $scope.result = result.data;
                                 });
                             }
                         }
                     }
                 }
             }
         }).state('accounting.yieldyear', {
             url: '/yieldyear',
             views: {
                 "accounting": {
                     templateUrl: 'Accounting/Yield',
                     controller: function ($scope, Deposit, Accounting) {

                         $scope.model = {};

                         $scope.calculate = function () {
                             if ($scope.depositForm.$valid) {
                                 Accounting.yieldyear($scope.model).then(function (result) {
                                     $scope.result = result.data;
                                 });
                             }
                         }
                     }
                 }
             }
         }).state('accounting.amount', {
             url: '/amount',
             views: {
                 "accounting": {
                     templateUrl: 'Accounting/Amount',
                     controller: function ($scope, Deposit, Accounting) {

                         $scope.model = {};

                         $scope.calculate = function () {
                             if ($scope.depositForm.$valid) {
                                 Accounting.amount($scope.model).then(function (result) {
                                     $scope.result = result.data;
                                 });
                             }
                         }
                     }
                 }
             }
         });;
}])
.run(
['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    $rootScope.bindErrors = function (form, items, model) {
        if (!form)
            return;
        angular.forEach(items, function (item) {

            if (item.Value && item.Value.Errors && item.Value.Errors.length != 0) {
                var control = form[item.Key];
                control.$error['server'] = true;
                if (!control.textErrors)
                    control.textErrors = {};
                control.textErrors['server'] = item.Value.Errors.map(function (error) { return error.ErrorMessage; }).join(",");
            }
        });
    }

    $rootScope.isActive = function (hash) {
        return { active: ($rootScope.$state.current.name == hash || ($rootScope.$state.$current.parent && ( $rootScope.$state.$current.parent.self.name == hash ||  
            $rootScope.$state.$current.parent.parent && $rootScope.$state.$current.parent.parent.self.name == hash)))
        };
    }

    $rootScope.toJavaScriptDate = function (value) {
        if (!value)
            return null;
        var pattern = /Date\(([^)]+)\)/;
        var results = pattern.exec(value);
        var dt = new Date(parseFloat(results[1]));
        return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
    }
}]).filter('percent', function () {
    return function (input) {
        return parseFloat(input) * 100 + "%";
    }
});